package com.kaiwukj.android.ufamily.mvp.ui.page.service.repairs;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.BaseSwipeBackActivity;
import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.di.component.DaggerServiceComponent;
import com.kaiwukj.android.ufamily.di.module.ServiceModule;
import com.kaiwukj.android.ufamily.mvp.helper.GlideEngine;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.RepairsResult;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.ImageAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.page.service.ServiceContract;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

import static com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt.RepairEveluate;


/**
 * @author Charles
 * @date 2019/8/22.
 * description：Kaiwu
 */
@Route(path = RepairEveluate)
public class RepairsEveluateActivity extends BaseSwipeBackActivity<RepairsPresenter> implements ServiceContract.RepairsView {

    @BindView(R.id.qtb_title)
    QMUITopBar qtbTitle;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.tv_edit_count)
    TextView tvEditCount;
    @BindView(R.id.rv_upload)
    RecyclerView rvUpload;
    @BindView(R.id.tv_commit)
    TextView tvCommit;

    @Autowired
    int repairId;

    ImageAdapter imageAdapter;

    private static final int REQUEST_CODE_CHOOSE_IMAGE = 1;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerServiceComponent.builder()
                .appComponent(appComponent)
                .serviceModule(new ServiceModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        ARouter.getInstance().inject(this);
        return R.layout.activity_repairs_eveluate;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tvEditCount.setText(String.format("%s/50", etContent.getText().toString().length()));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter.requestQIToken();
        qtbTitle.setTitle("评价");
        qtbTitle.addLeftBackImageButton().setOnClickListener(view -> finish());
        rvUpload.setLayoutManager(new GridLayoutManager(this, 3));
        List<String> imgs = new ArrayList<>();
        imageAdapter = new ImageAdapter(this, imgs);
        imageAdapter.setMaxCount(4);
        rvUpload.setAdapter(imageAdapter);
        imageAdapter.setOnItemClickListener(new ImageAdapter.onItemClickListener() {
            @Override
            public void onAddClick() {
                requestPermissions();
            }

            @Override
            public void onDelClick(int position) {
                imageAdapter.remove(position);
                // upImgs.remove(position);
            }

            @Override
            public void onImgClick(List<String> imgUrls, int position) {
            }
        });
        tvCommit.setOnClickListener(view -> {
            String content = etContent.getText().toString();
            if (TextUtils.isEmpty(content)) {
                showMessage("请输入评价内容");
                return;
            }
            mPresenter.evaluate(repairId, content, imageAdapter.getData());
        });
    }

    @SuppressLint("CheckResult")
    void requestPermissions() {
        RxPermissions rxPermission = new RxPermissions(this);
        Disposable disposable = rxPermission
                .requestEach(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                .subscribe(permission -> {
                    if (permission.granted) {
                        // 用户已经同意该权限
                        PictureSelector.create(this)
                                .openGallery(PictureMimeType.ofImage())
                                .isCompress(true)
                                .maxSelectNum(4 - imageAdapter.getDataCount())
                                .imageEngine(GlideEngine.createGlideEngine())
                                .theme(R.style.MyImagePickerStyle)
                                .forResult(new OnResultCallbackListener<LocalMedia>() {
                                    @Override
                                    public void onResult(List<LocalMedia> result) {
                                        //List<LocalMedia> list = PictureSelector.obtainMultipleResult(data);
                                        List<String> pathList = new ArrayList<>();
                                        for (LocalMedia media : result) {
                                            if (media.isCompressed()) {
                                                pathList.add(media.getCompressPath());
                                            }
                                        }
                                        imageAdapter.addData(pathList);
                                    }

                                    @Override
                                    public void onCancel() {

                                    }
                                });
                        //.forResult(PictureConfig.CHOOSE_REQUEST);

                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        showMessage("无法获取图片,请确认开启权限");

                    } else {
                        // 用户拒绝了该权限，并且选中『不再询问』
                        openSettingActivity(this, Settings.ACTION_APPLICATION_DETAILS_SETTINGS, "去打开读取权限以获取图片");
                    }
                });

        subscribe(disposable);
    }

    //@Override
    public void commitSuccess() {
        Toast.makeText(this, "提交成功", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent();
        intent.setAction(Constant.ACTION_REFRESH);
        sendBroadcast(intent);
        setResult(RESULT_OK);
        finish();
    }

    /*@Override
    public void showMessage(@NonNull String message) {
        QMUITipDialog dialog = new QMUITipDialog.Builder(this).setTipWord(message).create();
        dialog.setTitle(message);
        dialog.show();
        new Handler().postDelayed(dialog::dismiss, 800);
    }*/


    @Override
    public void onFetchRepairsList(List<RepairsResult> results) {

    }

    @Override
    public void onGetQiNiuToken(String token) {

    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        if (taskId == RepairsPresenter.COMMIT) {
            setResult(RESULT_OK);
            finish();
        }
    }
}
